package net.hancl.modules.sys.service.impl;

import net.hancl.common.bean.page.Query;
import net.hancl.common.bean.page.QueryResult;
import net.hancl.common.utils.copyo.BeanCopierUtils;
import net.hancl.modules.sys.bean.MenuBean;
import net.hancl.modules.sys.bean.RoleBean;
import net.hancl.modules.sys.dao.MenuMapper;
import net.hancl.modules.sys.dao.RoleMapper;
import net.hancl.modules.sys.entity.Menu;
import net.hancl.modules.sys.entity.Role;
import net.hancl.modules.sys.entity.RoleGroup;
import net.hancl.modules.sys.exception.ObjectExistException;
import net.hancl.modules.sys.service.IRoleService;
import net.hancl.modules.sys.vo.RoleVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleService implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    public QueryResult<Role> getRoleList(int page, int pagesize, RoleVo roleVo) {
        Query query = new Query();
        query.setBean(roleVo);
        query.setPageIndex(page);
        query.setPageSize(pagesize);

        QueryResult<Role> queryResult = new QueryResult<Role>();
        Long count = roleMapper.getCount(query);
        List<Role> list = roleMapper.queryPages(query);

        queryResult.setPages(count, pagesize);
        queryResult.setItems(list);
        return queryResult;
    }

    public RoleBean roleToBean(Role role){
        RoleBean roleBean = new RoleBean();
        BeanCopierUtils.copyProperties(role, roleBean);

        List<Menu> menus = menuMapper.getAllMenuByRoleId(role.getId());
        if(menus == null || menus.size() <= 0){
            return roleBean;
        }

        List<MenuBean> menuBeans = new ArrayList<MenuBean>();
        for ( Menu menu: menus
             ) {
            MenuBean menuBean = new MenuBean();
            BeanCopierUtils.copyProperties(menu, menuBean);
            menuBeans.add(menuBean);
        }
        roleBean.setMenus(menuBeans);
        return roleBean;
    }

    public List<Role> getRoleListAll() {
        return roleMapper.getRoleListAll();
    }

    public RoleBean get(int id) {
        Role role=roleMapper.get(id);
        return roleToBean(role);
    }

    public int del(int id) {
        //删除角色关联
        int i= roleMapper.del(id);
        if(i>0){
            return roleMapper.delRoleMenu(id);
        }
        return i;
    }

    public Role getByName(String name) {
        return roleMapper.getByName(name);
    }



    public List<RoleGroup> getGroupListAll() {
        return roleMapper.getGroupListAll();
    }
}
